package com.umgsai.wx.backend.test;

import com.alibaba.fastjson.JSON;

import java.util.List;

public class BinarySearch {

    public static void main(String[] args) {
        String source = "[1,5,9,11,67]";
        List<Integer> list = JSON.parseArray(source, Integer.class);

        int[] array = new int[list.size()];

        int i = 0;
        for (Integer integer : list) {
            array[i] = integer;
            i++;
        }
        System.out.println(binarySearch(array, -2));
        System.out.println(binarySearch(array, 3));
        System.out.println(binarySearch(array, list.get(0)));
        System.out.println(binarySearch(array, list.get(3)));
        System.out.println(binarySearch(array, list.get(4)));
        System.out.println(binarySearch(array, 65));
        System.out.println(binarySearch(array, 88));
    }

    public static boolean binarySearch(int[] array, int target) {
        if (target < array[0] || target > array[array.length - 1]) {
            return false;
        }
        int left = 0;
        int right = array.length - 1;
        while (left <= right) {
            int middle = (left + right) / 2;
            if (target < array[middle]) {
                right = middle - 1;
            } else if (target > array[middle]) {
                left = middle + 1;
            } else {
                return true;
            }
        }
        return false;
    }
}
